﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfSnqkGasAnalysis.Common;
using WpfSnqkGasAnalysis.IData;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis.IBusiness_impl
{
    /// <summary>
    /// 特殊气。业务处理
    /// </summary>
    /// 创建时间：2022-12-21 09:30:42。作者：王浩力
    public class TeshuBusiness : BaseBusiness
    {
        readonly ITeshu_gasDAL teshu_GasDAL = ServicesHelpter.GetService<ITeshu_gasDAL>();
        readonly ITeshu_gas_itemDAL teshu_Gas_ItemDAL = ServicesHelpter.GetService<ITeshu_gas_itemDAL>();
        readonly ITeshu_gas_update_logDAL teshu_Gas_Update_LogDAL = ServicesHelpter.GetService<ITeshu_gas_update_logDAL>();
        readonly ITeshu_gas_check_historyDAL teshu_Gas_Check_HistoryDAL = ServicesHelpter.GetService<ITeshu_gas_check_historyDAL>();
        readonly ISource_dictDAL source_DictDAL = ServicesHelpter.GetService<ISource_dictDAL>();

        /// <summary>
        /// 新增Teshu_gas
        /// </summary>
        /// <param name="teshu_Gas"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-21 09:33:04。作者：王浩力
        public IResult AddMain(Teshu_gas teshu_Gas)
        {
            #region 参数验证
            if (teshu_Gas == null)
            {
                return new Result("不可为空");
            }
            if (string.IsNullOrWhiteSpace(teshu_Gas.Report_no))
            {
                return new Result("报告编号不可为空");
            }
            if (string.IsNullOrWhiteSpace(teshu_Gas.Well_no))
            {
                return new Result("井号不可为空");
            }
            //if (teshu_Gas.Well_deep < 0)
            //{
            //    return new Result("井深不可为负数");
            //}
            if (teshu_Gas.Sample_temperature < 0)
            {
                return new Result("取样温度不可为负数");
            }
            if (string.IsNullOrWhiteSpace(teshu_Gas.Top_boundary))
            {
                return new Result("顶界层位不可为空");
            }
            if (string.IsNullOrWhiteSpace(teshu_Gas.Bottom_boundary))
            {
                return new Result("底界层位不可为空");
            }
            if (teshu_Gas.Oil_pressure < 0)
            {
                return new Result("油压不可为负数");
            }

            if (teshu_Gas.Casing_pressure < 0)
            {
                return new Result("套压不可为负数");
            }
            if (string.IsNullOrWhiteSpace(teshu_Gas.Sampling_location))
            {
                return new Result("取样位置不可为空");
            }
            if (string.IsNullOrWhiteSpace(teshu_Gas.Client))
            {
                return new Result("委托单位不可为空");
            }
            if (string.IsNullOrWhiteSpace(teshu_Gas.Sampler))
            {
                return new Result("取样人不可为空");
            }
            if (string.IsNullOrWhiteSpace(teshu_Gas.Analyst))
            {
                return new Result("分析人不可为空");
            }
            if (string.IsNullOrWhiteSpace(teshu_Gas.Sampling_unit))
            {
                return new Result("取样单位不可为空");
            }
            if (string.IsNullOrWhiteSpace(teshu_Gas.Sampling_time))
            {
                return new Result("采样时间不可为空");
            }
            if (string.IsNullOrWhiteSpace(teshu_Gas.Sampling_time))
            {
                return new Result("采样时间不可为空");
            }
            #endregion

            //检查编号重复  //创建时间：2023-1-15 18:45:06
            var page = Page(new Teshu_gas() { Report_no = teshu_Gas.Report_no }, 1, 1);
            if (page.Total > 0)
            {
                return new Result("编号重复了，请另取");
            }

            teshu_Gas.Input_user_id = CurrentLoginUser.Id;
            teshu_Gas.Input_real_name = CurrentLoginUser.User_real_name;
            teshu_Gas.Input_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            return teshu_GasDAL.Add(teshu_Gas);
        }

        /// <summary>
        /// 新增一条子项Teshu_gas_item
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-21 10:47:39。作者：王浩力
        public IResult AddTeshu_gasItem(Teshu_gas_item info)
        {
            if (info == null)
            {
                return new Result("info对象不可为空");
            }
            if (string.IsNullOrWhiteSpace(info.Analysis_time))
            {
                return new Result("分析时间不可为空");
            }
            if (info.S_mg_m3 < 0)
            {
                return new Result("总硫不可为负数");
            }
            if (info.H2s_mg_m3 < 0)
            {
                return new Result("H2S不可为负数");
            }
            if (info.Teshu_gas_id <= 0)
            {
                return new Result("Teshu_gas_id必须大于0");
            }
            //条数限制。2023-1-12 17:34:19
            var list = GetTeshu_gas_itemList(info.Teshu_gas_id);
            int limitAmount = 9;
            if (list != null && list.Count >= limitAmount)
            {
                return new Result($"最多录入{limitAmount}条");
            }
            return teshu_Gas_ItemDAL.Add(info);
        }

        /// <summary>
        /// 根据Teshu_gas主键查询Teshu_gas_item列表
        /// </summary>
        /// <param name="teshuMainKey"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-21 11:06:42。作者:王浩力
        public List<Teshu_gas_item> GetTeshu_gas_itemList(long teshuMainKey)
        {
            return teshu_Gas_ItemDAL.GetList(teshuMainKey);
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="teshu_Gas">查询条件</param>
        /// <param name="p">页码</param>
        /// <param name="rows">每页显示条数</param>
        /// <returns></returns>
        /// 创建时间：2022-12-21 14:23:25。作者：王浩力
        public PageModel<Teshu_gas> Page(Teshu_gas teshu_Gas, int p, int rows)
        {
            if (CurrentLoginUser.Role_id == "校对人")
            {
                teshu_Gas.WorkList = new List<int>() { 1, 3 };
            }
            else if (CurrentLoginUser.Role_id == "审核人")
            {
                teshu_Gas.WorkList = new List<int>() { 2 };
            }

            //步骤下拉框查询，添加时间：2023-1-16 17:58:28。
            if (teshu_Gas.O_step!=null && teshu_Gas.O_step != -1)   
            {
                teshu_Gas.WorkList = new List<int>() { (int)teshu_Gas.O_step };
            }

            return teshu_GasDAL.Page(teshu_Gas, p, rows);
        }

        /// <summary>
        /// 删除一条Teshu_gas_item
        /// </summary>
        /// <param name="teshuGasItemKey"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-21 16:09:20。作者：王浩力
        public IResult DeleteTeshuGasItem(long teshuGasItemKey)
        {
            return teshu_Gas_ItemDAL.Delete(teshuGasItemKey);
        }

        /// <summary>
        /// 编辑teshu_Gas
        /// </summary>
        /// <param name="teshu_Gas"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-21 17:03:42。作者：王浩力
        public IResult Edit(Teshu_gas teshu_Gas)
        {
            var old = teshu_GasDAL.Get(teshu_Gas.Id);
            if (old != null && old.O_step == 3)
            {
                teshu_Gas.O_step = 1;
            }
            if (old.O_step == 1 && teshu_Gas.O_step == null)
            {
                teshu_Gas.O_step = 1;
            }

            //检查编号重复  //创建时间：2023-1-15 18:45:06
            if (old.Report_no != teshu_Gas.Report_no)
            {
                var page = Page(new Teshu_gas() { Report_no = teshu_Gas.Report_no }, 1, 1);
                if (page.Total > 0)
                {
                    return new Result("编号重复了，请另取");
                }
            }

            return teshu_GasDAL.Edit(teshu_Gas);
        }

        /// <summary>
        /// 校对
        /// </summary>
        /// <param name="teshu_Gas"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-21 17:34:31。作者：王浩力
        public IResult Proofread(Teshu_gas teshu_Gas)
        {
            var old = teshu_GasDAL.Get(teshu_Gas.Id);
            if (old == null)
            {
                return new Result("没找到记录");
            }

            //检查编号重复  //创建时间：2023-1-15 18:45:06
            if (old.Report_no != teshu_Gas.Report_no)
            {
                var page = Page(new Teshu_gas() { Report_no = teshu_Gas.Report_no }, 1, 1);
                if (page.Total > 0)
                {
                    return new Result("编号重复了，请另取");
                }
            }

            //校对人id。添加时间：2023-1-9 00:12:55。
            teshu_Gas.Proofread_user_id = CurrentLoginUser.Id;

            teshu_Gas.Proofread_real_name = CurrentLoginUser.User_real_name;
            teshu_Gas.Proofread_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            teshu_Gas.O_step = 2;
            var result = teshu_GasDAL.Edit(teshu_Gas);
            return result;
        }

        /// <summary>
        /// 审核处理
        /// </summary>
        /// <param name="teshu_Gas"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-22 13:51:27。作者：王浩力
        public IResult Check(Teshu_gas_check_history info)
        {
            if (info == null)
            {
                return new Result("无效参数");
            }
            if (info.Check_stat == 0 && string.IsNullOrWhiteSpace(info.Reject_reason))
            {
                return new Result("驳回理由不可为空");
            }
            info.Check_user_id = CurrentLoginUser.Id;
            info.Check_user_name = CurrentLoginUser.User_real_name;
            info.Check_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            return teshu_GasDAL.Check(info);
        }

        /// <summary>
        /// 删除Teshu_gas
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-23 09:37:45。作者：王浩力
        public IResult Delete(long id)
        {
            var info = teshu_GasDAL.Get(id);
            if (info.O_step == 4)
            {
                return new Result("审核通过的记录不可删除");
            }
            var result = teshu_GasDAL.Delete(new Teshu_gas() { Id = id });
            return result;
        }

        /// <summary>
        /// 获取操作 日志
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-22 15:37:16。
        public List<Teshu_gas_check_history> GetTeshuStepLog(long id)
        {
            List<Teshu_gas_check_history> list = new List<Teshu_gas_check_history>();
            var old = teshu_GasDAL.Get(id);
            //修改记录
            var uplogList = teshu_Gas_Update_LogDAL.GetList(id);
            if (uplogList != null && uplogList.Count > 0)
            {
                uplogList = uplogList.FindAll(g => g.Data_version >= 1);
            }
            //审核历史
            var history = teshu_Gas_Check_HistoryDAL.GetList(id);

            Teshu_gas_check_history s1 = new Teshu_gas_check_history();
            s1.Check_time = old.Input_time;
            s1.Reject_reason = "录入";
            s1.Check_user_name = old.Input_real_name;
            list.Add(s1);

            if (uplogList?.Count > 0)
            {
                foreach (var item in uplogList)
                {
                    if (string.IsNullOrWhiteSpace(item.Update_time))
                    {
                        continue;
                    }
                    Teshu_gas_check_history s2 = new Teshu_gas_check_history();
                    s2.Check_time = item.Update_time;
                    s2.Reject_reason = "校对编辑";
                    s2.Check_user_name = item.Update_real_name;
                    list.Add(s2);
                }
            }

            //添加时间：2023-1-9 00:33:45。作者：王浩力
            Teshu_gas_check_history s4 = new Teshu_gas_check_history();
            s4.Check_time = old.Proofread_time;
            s4.Reject_reason = "校对";
            s4.Check_user_name = old.Proofread_real_name;
            list.Add(s4);

            if (history?.Count > 0)
            {
                foreach (var item in history)
                {
                    Teshu_gas_check_history s2 = new Teshu_gas_check_history();
                    s2.Check_time = item.Check_time;
                    s2.Reject_reason = item.Check_stat == 1 ? "审核" : item.Reject_reason;
                    s2.Check_user_name = item.Check_user_name;
                    list.Add(s2);
                }
            }
            list = list.OrderBy(g => g.Check_time).ToList();
            return list;
        }

        /// <summary>
        /// 读取下拉框的数据为文本。
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-22 17:13:02。作者：王浩力
        public TeshuGasView GetView(long id)
        {
            var info = teshu_GasDAL.Get(id);
            var mapper = EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<Teshu_gas, TeshuGasView>();
            var viewInfo = mapper.Map(info);

            //添加时间：2023-1-8 23:52:13。
            UserBusiness userBusiness = new UserBusiness();
            var userList = userBusiness.GetAllUser();

            var all = source_DictDAL.GetAll();
            all = all.FindAll(g => g.D_stat == 1);

            //取样位置 //修改时间：2023-1-15 18:24:26。
            if (System.Text.RegularExpressions.Regex.IsMatch(viewInfo.Sampling_location, "^\\d{1,19}"))
            {
                viewInfo.Sampling_locationStr = all.FirstOrDefault(g => g.Id == viewInfo.Sampling_location.ToMyInt64())?.Item_name;
            }
            else
            {
                viewInfo.Sampling_locationStr = viewInfo.Sampling_location;
            }

            viewInfo.ClientStr = all.FirstOrDefault(g => g.Id == viewInfo.Client.ToMyInt64())?.Item_name;

            //取样人             
            viewInfo.SamplerStr = userList.FirstOrDefault(g => g.Id == viewInfo.Sampler.ToMyInt64())?.User_real_name;

            viewInfo.Sampling_unitStr = all.FirstOrDefault(g => g.Id == viewInfo.Sampling_unit.ToMyInt64())?.Item_name;
            viewInfo.Top_boundaryStr = all.FirstOrDefault(g => g.Id == viewInfo.Top_boundary.ToMyInt64())?.Item_name;
            viewInfo.Bottom_boundaryStr = all.FirstOrDefault(g => g.Id == viewInfo.Bottom_boundary.ToMyInt64())?.Item_name;

            //分析人姓名
            viewInfo.AnalystStr = userList.FirstOrDefault(g => g.Id == viewInfo.Analyst.ToMyInt64())?.User_real_name;
            viewInfo.teshu_Gas_Items = teshu_Gas_ItemDAL.GetList(id);

            //分析人，电子签名
            viewInfo.E6 = userList.FirstOrDefault(g => g.Id == info.Analyst.ToMyInt64())?.SignatureImgPath;

            //校对人，电子签名
            if (info.Proofread_user_id.HasValue && info.Proofread_user_id > 0)
            {
                viewInfo.E7 = userList.FirstOrDefault(g => g.Id == info.Proofread_user_id)?.SignatureImgPath;
            }

            //审核人，电子签名
            //审核历史
            var history = teshu_Gas_Check_HistoryDAL.GetList(id);
            if (history?.Count > 0)
            {
                var find = history.OrderByDescending(g => g.Id).FirstOrDefault();
                if (find != null)
                {
                    var ckUser = userList.FirstOrDefault(g => g.Id == find.Check_user_id);
                    viewInfo.E5 = find?.Check_user_name;//审核人姓名
                    viewInfo.E8 = ckUser?.SignatureImgPath; //审核人电子签名图片url
                }
            }


            return viewInfo;
        }

    }
}
